package com.bijava.service.impl;

import com.bijava.config.MinIOConfig;
import com.bijava.config.ParamConfig;
import com.bijava.service.UploadService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author bijava
 * @version 1.0
 * @since 20-9-8
 */
@Service
public class UploadServiceImpl implements UploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadServiceImpl.class) ;
    @Resource
    private ParamConfig paramConfig;

    // 上传 <html> ,返回服务器地址
    @Override
    public String uploadHtml(String fileName, String filePath) throws Exception {
        MinioClient minioClient = MinIOConfig.getMinioClient();
        String bucketNameHtml = paramConfig.getBucketNameHtml();
        boolean bucketExists = minioClient.bucketExists(bucketNameHtml);
        if (!bucketExists){
            LOGGER.info("{}不存在",bucketNameHtml);
            minioClient.makeBucket(bucketNameHtml);
        }
        minioClient.putObject(bucketNameHtml,fileName,filePath,null);
        return paramConfig.getEndpoint()+"/"+bucketNameHtml+"/"+fileName ;
    }

    // 上传 <img> ,返回服务器地址
    @Override
    public String uploadImg(String imgName, String imgPath) throws Exception {
        MinioClient minioClient = MinIOConfig.getMinioClient();
        String bucketNameImage = paramConfig.getBucketNameImage();
        boolean bucketExists = minioClient.bucketExists(bucketNameImage);
        if (!bucketExists){
            LOGGER.info("{}不存在",bucketNameImage);
            minioClient.makeBucket(bucketNameImage);
        }

        minioClient.putObject(bucketNameImage,imgName,imgPath,null);
        minioClient.putObject(bucketNameImage,"test/"+imgName,imgPath,null);
        return paramConfig.getEndpoint()+"/"+bucketNameImage+"/"+imgName ;
    }

    @Override
    public String uploadString(){
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            builder.append(
                    "Sphinx of black quartz, judge my vow: Used by Adobe InDesign to display font samples. ");
            builder.append("(29 letters)\n");
            builder.append(
                    "Jackdaws love my big sphinx of quartz: Similarly, used by Windows XP for some fonts. ");
            builder.append("(31 letters)\n");
            builder.append(
                    "Pack my box with five dozen liquor jugs: According to Wikipedia, this one is used on ");
            builder.append("NASAs Space Shuttle. (32 letters)\n");
            builder.append(
                    "The quick onyx goblin jumps over the lazy dwarf: Flavor text from an Unhinged Magic Card. ");
            builder.append("(39 letters)\n");
            builder.append(
                    "How razorback-jumping frogs can level six piqued gymnasts!: Not going to win any brevity ");
            builder.append("awards at 49 letters long, but old-time Mac users may recognize it.\n");
            builder.append(
                    "Cozy lummox gives smart squid who asks for job pen: A 41-letter tester sentence for Mac ");
            builder.append("computers after System 7.\n");
            builder.append(
                    "A few others we like: Amazingly few discotheques provide jukeboxes; Now fax quiz Jack! my ");
            builder.append("brave ghost pled; Watch Jeopardy!, Alex Trebeks fun TV quiz game.\n");
            builder.append("---\n");
        }
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));

            MinioClient minioClient = MinIOConfig.getMinioClient();
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(
                            paramConfig.getBucketNameHtml())
                            .object("stringbuffer")
                            .stream(bais, bais.available(), -1)
                            .build());
            bais.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }

    @Override
    public List<Bucket> bucketList() {
        MinioClient minioClient = MinIOConfig.getMinioClient();
        try {
            String bucketNameImage = paramConfig.getBucketNameImage();
            //获取所有的桶（即根路径的文件夹）
            List<Bucket> buckets = minioClient.listBuckets();
            for (Bucket bucket : buckets) {
                System.out.println(bucket.creationDate()+"-------"+bucket.name());
            }

            //获取指定桶下面的所有对象
            Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketNameImage).build());
            for (Result<Item> result : results) {
                Item item = result.get();
                System.out.println(item.size()+"----"+item.objectName()+"----"+item.versionId());
            }

            String objectUrl = minioClient.getObjectUrl(bucketNameImage, "2020072702.jpg");
            LOGGER.info("图片地址为{}",objectUrl);

        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (InsufficientDataException e) {
            e.printStackTrace();
        } catch (InternalException e) {
            e.printStackTrace();
        } catch (InvalidBucketNameException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidResponseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (XmlParserException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void download(HttpServletResponse response) {
        MinioClient minioClient = MinIOConfig.getMinioClient();
        try {
            OutputStream outputStream = response.getOutputStream();

            InputStream is = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(paramConfig.getBucketNameHtml())
                            .object("1285041140.xls")
                            .build());

            byte[] buf = new byte[10240];
            int reader = is.read(buf);
            while (reader != -1) {
                outputStream.write(buf, 0, reader);
                reader = is.read(buf);
                outputStream.flush();
            }

            is.close();
        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (InsufficientDataException e) {
            e.printStackTrace();
        } catch (InternalException e) {
            e.printStackTrace();
        } catch (InvalidBucketNameException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidResponseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (XmlParserException e) {
            e.printStackTrace();
        }
    }
}